import { _decorator, Component, Node, director, Label, Prefab, instantiate, view, Layout, game } from 'cc';
const { ccclass, property } = _decorator;
import { Util } from './Util';
import { GameData, GameState } from './GameData';
import { Sun } from './Sun';
import { AudioController } from './AudioController';
const gameData = GameData.getInstance()

@ccclass('Main')
export class Main extends Component {
    @property(Node)
    gameOverUI =  null;

    @property(Node)
    startGameUI =  null;

    @property(Label)
    totalSunEnergyLabel = null

    @property(Prefab)
    sunEnergyPrefab = null

    @property(Node)
    mainNode = null

    sunEnergyInterval = 3 // 3秒生产一个
    audioController = null

    start() {
        this.totalSunEnergyLabel.string = gameData.totalSunEnergy
        
        this.mainNode.getChildByName('ChooseMenu').getComponent(Layout).enabled = false
        this.audioController = this.node.getComponent(AudioController)
        this.audioController.playMainBgm()
        this.startCreateSunEnergy()

        director.preloadScene('over')
    }
    createSunEnergy(){
        if(gameData.gameSate !== GameState.ready) return;

        let sun = instantiate(this.sunEnergyPrefab);
        this.mainNode.addChild(sun);
        const width = view.getDesignResolutionSize().width - 200
        sun.setPosition(Util.getRandomOpen(-width / 2, width / 2), 375) // 设置初始位置
        sun.getComponent(Sun).drop() //开始掉落
    }
    startCreateSunEnergy(){
        this.schedule(this.createSunEnergy, this.sunEnergyInterval)
    }
    stopCreateSunEnergy(){
        this.unschedule(this.createSunEnergy)
    }
    update(deltaTime: number) {
        this.totalSunEnergyLabel.string = gameData.totalSunEnergy
    }

    setGameOver(){
        gameData.gameSate = GameState.gameOver
        this.gameOverUI.active = true
        this.audioController.stop();
    }
    isGameOver(){
        return gameData.gameSate === GameState.gameOver
    }
}

